package com.du.web.sample.util;

import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;

public class AppSecretUtil {

    private static SecureRandom random = new SecureRandom();
    public static String generateSecret() {
        byte[] bytes = new byte[24]; // 48字节编码为64字符Base64
        random.nextBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }

    public static String generateUniqueAppSecret() {
        String secret;
        // 使用UUID、时间戳和随机数组合生成更唯一的种子
        String base = UUID.randomUUID().toString().replace("-", "") +
                Long.toHexString(Instant.now().toEpochMilli()) +
                Integer.toHexString(random.nextInt());
        return convertToAppSecretFormat(base);
    }

    private static String convertToAppSecretFormat(String base) {
        // 字符池
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 使用SHA-256哈希确保均匀分布
        byte[] hash = sha256(base.getBytes());
        StringBuilder result = new StringBuilder();
        // 确保至少包含一个大写字母、一个小写字母和一个数字
        result.append(chars.charAt((hash[0] & 0xFF) % 26));
        result.append(chars.charAt(26 + ((hash[1] & 0xFF) % 26)));
        result.append(chars.charAt(52 + ((hash[2] & 0xFF) % 10)));

        // 生成剩余的29个字符
        for (int i = 0; i < 29; i++) {
            int index = (hash[3 + i % (hash.length - 3)] & 0xFF) % chars.length();
            result.append(chars.charAt(index));
        }
        return result.toString();
    }

    private static byte[] sha256(byte[] input) {
        try {
            java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
            return digest.digest(input);
        } catch (Exception e) {
            throw new RuntimeException("SHA-256算法不可用", e);
        }
    }

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        String secret = generateSecret();
        System.out.println("Generated Secret: " + secret);
        System.out.println("Length: " + secret.length());
        System.out.println("time: " + (System.currentTimeMillis() - l));

        long l2 = System.currentTimeMillis();
        String secret2 = generateUniqueAppSecret();
        System.out.println("Generated Secret: " + secret2);
        System.out.println("Length: " + secret2.length());
        System.out.println("time: " + (System.currentTimeMillis() - l2));
    }

}
